package com.syh.companyservice.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syh.bscommon.pojo.Log;
import com.syh.bscommon.pojo.Result;
import com.syh.companyservice.mapper.CompaniesMapper;
import com.syh.companyservice.pojo.Companies;
import com.syh.companyservice.service.ICompaniesService;
import com.syh.feignapi.clients.CreditsClient;
import com.syh.feignapi.clients.LogClient;
import com.syh.feignapi.pojo.CarbonCredits;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author syh 86187
 * @date 2024/7/1
 * com.syh.bishe.service.impl
 * @description
 */
@Service
@RequiredArgsConstructor
public class ICompaniesServiceImpl extends ServiceImpl<CompaniesMapper, Companies> implements ICompaniesService {
    private final CompaniesMapper companiesMapper;
    private final CreditsClient creditsClient;
    private final LogClient logClient;

    @Override
    @Transactional
    public void add(Companies companies) {
        Companies one = lambdaQuery().eq(Companies::getName, companies.getName()).one();
        if (one != null) {
            companies.setId(one.getId());
            companiesMapper.updateById(companies);
        } else {
            companiesMapper.insert(companies);
            CarbonCredits carbonCredits = new CarbonCredits().setCompanyId(companies.getId()).setCreditAmount(BigDecimal.valueOf(10000000.0)).setAccount(BigDecimal.valueOf(0.0));
            creditsClient.setinfo(carbonCredits);
        }
    }

    @Override
    public Integer getId(String name) {
        Integer id = companiesMapper.getId(name);
        return id;
    }

    @Override
    public Companies getName(Integer id) {
        Companies companies = companiesMapper.getCompany(id);
        return companies;
    }

    @Override
    public Integer check(String name) {
        return companiesMapper.check(name);
    }

    @Override
    public Result addCompanies(Companies companies) {
        try {
            add(companies);
            logClient.addLog(new Log().setInfo("公司：" + companies.getName()+"录入信息").setDate(LocalDateTime.now()));
        }catch (Exception e) {
            return Result.error("出现错误");
        }
        return Result.success();
    }
}
